var cli=require('mongodb').MongoClient;
var ObjectID=require('mongodb').ObjectID;
var mock=require('./mock');
var settings=require('../settings');

function Comment(_id,user,content){
    var d=new Date();
    this._id=_id;
    this.user=user;
    this.content=content;
    this.time=mock.dateFormat(d,'all',true);
}

module.exports=Comment;

Comment.prototype.save= function (cb) {
    var comment=this;
    cli.connect(settings.dbUrl,function (err, db) {
        if(err)return db.close(),cb(err);
        db.collection('posts', function (err, coll) {
            if(err)return db.close(),cb(err);
            coll.update({_id:new ObjectID(comment._id)},{$push:{comments:{user:comment.user,content:comment.content,time:comment.time}}}, function (err, ret) {
                db.close();
                if(err)return cb(err);
                cb(null,ret);
            });
        });
    });
}